//
//  QJCodePayVC.m
//  QuanJieShopProject
//
//  Created by apple on 2018/3/2.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "QJCodePayVC.h"
//支付宝SDK
#import <AlipaySDK/AlipaySDK.h>
//微信
#import "WXApiManager.h"
@interface QJCodePayVC () <WXApiManagerDelegate>
@property (nonatomic, assign) YFPayType payType;
@property (nonatomic, strong) UIButton *selectBtn;
@end

@implementation QJCodePayVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.mobileLabel.text = self.codeStr;
    self.mobileLabel.enabled = NO;
    [self defaultUIPrepare];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
    //控件不被导航栏遮挡
    self.navigationController.navigationBar.translucent = NO;
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    //控件不被导航栏遮挡
    self.navigationController.navigationBar.translucent = YES;
}
#pragma mark -- 默认配置
- (void)defaultUIPrepare{
    self.title = @"扫码支付";
    self.yeBtn.selected = YES;
    self.payType = YFPayType_Balance;
    self.selectBtn = self.yeBtn;
    self.selectBtn.tag = self.yeBtn.tag;
    
    //支付宝支付成功通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alipayGengXingData) name:@"alipaysuccsed" object:nil];
    //支付宝支付失败通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alipayErrorAction) name:@"alipayerror" object:nil];
    //微信支付
    [WXApiManager sharedManager].delegate = self;
}
- (IBAction)payActionBtnClickAction:(UIButton *)sender {
    NSInteger tag = sender.tag;
    if (self.selectBtn.tag == tag) {
        //点击的是相同的按钮
    }else{
        switch (tag) {
            case 200:
            {
                self.yeBtn.selected = YES;
                self.selectBtn.selected = NO;
                self.payType = YFPayType_Balance;
                self.selectBtn = self.yeBtn;
                self.selectBtn.tag = self.yeBtn.tag;
                self.selectBtn.selected = YES;
            }
                break;
            case 201:
            {
                self.aliBtn.selected = YES;
                self.selectBtn.selected = NO;
                self.payType = YFPayType_Ali;
                self.selectBtn = self.aliBtn;
                self.selectBtn.tag = self.aliBtn.tag;
                self.selectBtn.selected = YES;
            }
                break;
            case 202:
            {
                self.wxBtn.selected = YES;
                self.selectBtn.selected = NO;
                self.payType = YFPayType_WeiXin;
                self.selectBtn = self.wxBtn;
                self.selectBtn.tag = self.wxBtn.tag;
                self.selectBtn.selected = YES;
            }
                break;
                
            default:
                break;
        }
    }
}
- (IBAction)okPayBtnClickAction:(UIButton *)sender {
    WEAKSELF
    NSString *moneyStr = self.moneyTF.text ? self.moneyTF.text : @"";
    if (moneyStr.length > 0) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:self.codeStr forKey:@"shop_user_mobile"];
        [dict setObject:moneyStr forKey:@"amount"];
        [dict setObject:@"submit_order" forKey:@"act"];
    
#warning 线下支付没有余额支付, 只有支付宝跟微信
        NSLog(@"线下支付 dict = %@", dict);
        [WWNetRequest fetchPayOffLineWithParameters:dict success:^(id response) {
            NSLog(@"线下支付 response = %@", response);
            NSString *orderID = response[@"data"][@"order_id"];
            [weakSelf pushPayTypeGetPayInfo:orderID];
        } failure:^(NSDictionary *error) {
            NSLog(@"线下支付 error = %@", error);
            [MBPHUD showAlertWithTitle:@"订单提交失败"];
        }];
    }else{
        [MBPHUD showAlertWithTitle:@"支付金额不能为空!"];
    }
}

// 上传支付类型, 获取订单支付信息
- (void)pushPayTypeGetPayInfo:(NSString *)orderID {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:orderID forKey:@"order_id"];
    if (self.payType == YFPayType_Ali) {   // 支付宝
        [dict setObject:@"alipayapp" forKey:@"pay_code"];
    }else if (self.payType == YFPayType_WeiXin) {  // 微信
        [dict setObject:@"appWeixinPay" forKey:@"pay_code"];
    }else if (self.payType == YFPayType_Balance){
        
         [dict setObject:@"balance" forKey:@"pay_code"];
    }
    NSLog(@"线下支付 dict = %@", dict);
    WEAKSELF
    [WWNetRequest fetchPayOffLinePayTypeWithParameters:dict success:^(id response) {
        NSLog(@"线下支付 response = %@", response);
        
        [weakSelf payOrderActionWithPayStr:response];
    } failure:^(NSDictionary *error) {
        NSLog(@"线下支付 error = %@", error);
        [MBPHUD showAlertWithTitle:@"支付失败"];
        
    }];
    
    
}


#pragma mark -- 支付方法
- (void)payOrderActionWithPayStr:(id)payStr{
    if (self.payType == YFPayType_Ali) {
        NSString *responseStr = [NSString stringWithFormat:@"%@",payStr[@"data"]];
        //支付宝
        [[AlipaySDK defaultService] payOrder:responseStr fromScheme:MyAppScheme callback:^(NSDictionary *resultDic) {
            
            if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                //支付成功
                [[NSNotificationCenter defaultCenter] postNotificationName:@"alipaysuccsed" object:resultDic];
            }else{
                //支付失败
                [[NSNotificationCenter defaultCenter] postNotificationName:@"alipayerror" object:resultDic];
            }
            
        }];
    }else if (self.payType == YFPayType_WeiXin){
        //微信
        //时间戳
        //time_t now;
        //time(&now);
        //NSString *stamp  = [NSString stringWithFormat:@"%ld", now];
        if ([payStr isKindOfClass:[NSDictionary class]]) {
            PayReq *req = [[PayReq alloc]init];
            req.partnerId = [payStr objectForKey:@"partnerid"];
            req.prepayId = [payStr objectForKey:@"prepayid"];
            req.nonceStr = [payStr objectForKey:@"noncestr"];
            NSString *time = [payStr objectForKey:@"timestamp"];
            req.timeStamp = [time intValue];
            req.package = [payStr objectForKey:@"package"];
            req.sign = [payStr objectForKey:@"sign"];
            [WXApi sendReq:req];
        }
    }else{
        //余额
        [MBPHUD showAlertWithTitle:@"余额支付成功"];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}
#pragma mark -- 支付宝充值成功刷新数据
- (void)alipayGengXingData{
    [MBPHUD showAlertWithTitle:@"支付宝支付成功!"];
    [UIView animateWithDuration:1.0f animations:^{
        KPopViewControllerAction;
    }];
}
#pragma mark -- 支付宝充值失败的提示
- (void)alipayErrorAction{
    [MBPHUD showAlertWithTitle:@"支付宝支付失败!"];
    [UIView animateWithDuration:1.0f animations:^{
        KPopViewControllerAction;
    }];
}
#pragma mark -- 微信支付成功回调方法
- (void)managerDidPaySucced{
    static dispatch_once_t disOnce;
    
    dispatch_once(&disOnce,^ {
        
        [MBPHUD showAlertWithTitle:@"微信支付成功!"];
        [UIView animateWithDuration:1.0f animations:^{
            
            KPopViewControllerAction;
            
        }];
        
    });
}
#pragma mark -- 微信支付失败回调方法
- (void)managerDidPayFailed{
    

    [MBPHUD showAlertWithTitle:@"微信支付失败!"];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
